package cn.tedu.charging.order.timer;

import cn.tedu.charging.common.pojo.po.ChargingBillExceptionPO;
import cn.tedu.charging.common.pojo.po.ChargingBillSuccessPO;
import cn.tedu.charging.common.protocol.WebSocketMessage;
import cn.tedu.charging.order.endpoint.WebSocketServer;
import cn.tedu.charging.order.feign.DeviceClient;
import cn.tedu.charging.order.mapper.BillExceptionMapper;
import cn.tedu.charging.order.mapper.BillSuccessMapper;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 检查订单异常的定时
 */
@Component
@Slf4j
public class OrderExceptionJob {
    @Autowired
    private BillSuccessMapper billSuccessMapper;
    @Autowired
    private BillExceptionMapper billExceptionMapper;
    @Autowired
    private DeviceClient deviceClient;
    @Autowired
    private WebSocketServer webSocketServer;
    @XxlJob("order-status-check")
    public void checkOrderStatus(){
        log.info("订单异常状态检查 定时任务开始执行");
        //1.拿到定时任务参数,创建定时人的程序,一定填写订单编号
        String billId= XxlJobContext.getXxlJobContext().getJobParam();
        //2.利用successMapper读取当前编号对应的订单
        ChargingBillSuccessPO success=getSuccessByBillId(billId);
        //3.判断是否订单异常 success!=null&&success.status==1
        if (success!=null&&success.getBillStatus()==1){
            //4.应该按照订单异常流程处理 存储异常 异常单和success有关联
            saveExceptionBill(success);
            //UNDO 通知更新设备状态
            // 通知用户 拔枪结账走人 异常抱歉 送个优惠券
            WebSocketMessage webSocketMessage=new WebSocketMessage();
            webSocketMessage.setState(1);
            webSocketMessage.setMessage("不ok");
            webSocketMessage.setData("A订单充电异常,请换枪,对不起,送您一张优惠券");
            webSocketServer.sendMsg2User(success.getUserId(), JSON.toJSONString(webSocketMessage));
        }
    }
    private void saveExceptionBill(ChargingBillSuccessPO success) {
        //组织一个异常单 po 写入数据库
        ChargingBillExceptionPO po=new ChargingBillExceptionPO();
        po.setBillId(success.getBillId());//必须填
        po.setCreateTime(new Date());
        billExceptionMapper.insert(po);
    }
    private ChargingBillSuccessPO getSuccessByBillId(String billId) {
        //select * from charging_bill_success where bill_id=?
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("bill_id",billId);
        return billSuccessMapper.selectOne(queryWrapper);
    }
}
